package com.zishi.util;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.tomcat.jni.Sockaddr;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;

public class ConnectionPy {
    public  static  String remoteCall(String imgPath, String posture, String userId, String root_dir, boolean is_squat, String imgPath2) {
        JSONObject jsonObject = new JSONObject();
        //通过将json对象转化为字符串(字节流)传输
        jsonObject.put("imgPath", imgPath);
        jsonObject.put("posture", posture);
        jsonObject.put("userId", userId);
        jsonObject.put("root_dir", root_dir);
        //当识别squat时，imgPath为正面照路径，imgPath2为侧身照路径
        if (is_squat) {
            jsonObject.put("imgPath2", imgPath2);
        }
        String str = jsonObject.toJSONString();
        // 访问服务进程的套接字
        Socket socket = null;
        Socket socket1 = null;

        String jsonPath = null;
        OutputStream os = null;
        InputStream is = null;
        System.out.println("py - 1");
        try {
            // 初始化套接字，设置访问服务的主机和进程端口号，HOST是访问python进程的主机名称，可以是IP地址或者域名，PORT是python进程绑定的端口号
//            String HOST = InetAddress.getLocalHost().getHostAddress();

            socket = new Socket("127.0.0.1", 12345);
            // 获取输出流对象
            os = socket.getOutputStream();
            PrintStream out = new PrintStream(os);
            // 发送内容
            out.print(str);
            // 告诉服务进程，内容发送完毕，可以开始处理
            out.print("over");
//            socket.shutdownOutput();

            System.out.println("py - 2");
            // 获取服务进程的输入流
            is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
            String tmp = null;
//            socket.shutdownInput();

            jsonPath = br.readLine();
            System.out.println(jsonPath);

        } catch (IOException e) {
            e.printStackTrace();
        }
//        finally  {
//            try {
//                if (socket != null) {
//                    System.out.println("\n\n\n\n\nclose\nclose\n\n\n\n");
//                    socket.close();
//                }
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//
//        }

        return jsonPath;
    }


    //  同样使用根目录+用户openid的方式
    public static JSONObject connectionPy(List<String> inputImgPath, String outputDir, String posture, boolean isSquat) throws UnknownHostException {

        String outputImgName = UUID.randomUUID().toString();
        String inputImgPath1 = inputImgPath.get(0);
        String inputImgPath2 = "";
        inputImgPath1 = TrainingPathChangeUtil.changeWebPathToLocal(inputImgPath1);
        if (isSquat) {
            inputImgPath2 = inputImgPath.get(1);
            inputImgPath2 = TrainingPathChangeUtil.changeWebPathToLocal(inputImgPath2);
        }
        System.out.println("inputImgPath1: " + inputImgPath1 + "\n" + "inputImgPath2: " + inputImgPath2 + "\n" +
                "posture: " + posture + "\n" + "outputImgName: " + outputImgName + "\n" +
                "outputDir: " + outputDir + "\n" + "isSquat: " + isSquat);

        String jsonPath = remoteCall(inputImgPath1, posture, outputImgName, outputDir, isSquat, inputImgPath2);
        System.out.println("2222: " + jsonPath);
        String s = readJsonFile(jsonPath);//json文件转为字符串和
        JSONObject jsonObj = JSON.parseObject(s);//字符串转为json对象
        System.out.println("problem: " + jsonObj.getString("problem"));
        System.out.println("userImg: " + jsonObj.getString("userImg"));
        System.out.println("score: " + jsonObj.getString("score"));
        if (isSquat) {
            System.out.println("useImg2" + jsonObj.getString("userImg2"));
        }

        return jsonObj;
    }


    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            System.out.println("1111111: " + fileName);
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


}
